<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽会员训练计划查询</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body style="background-color: rgb(254, 254, 255);">
    {% include 'show_ins_info.html' %}
    <hr>
    <h2>会员训练计划查询</h2>
    <div class="form-row">
        <!-- <div style="color:rgb(186, 181, 143);width:100px;font-weight: bold;font-size:14px;" >会员ID及姓名 </div > -->
        <h5 style="margin:5px;width:100px;">会员ID及姓名</h5>
        <input id='cusName' style="width:100px;" oninput="handleCusNameInput()" onclick="handleCusNameInput()">    
        <div id="cusNameList" style="display:none;"></div>
    </div>   

    <div id="selectInsBox" class="form-row" style="flex-flow:row;margin-top:15px;">
        <div><h5 style="margin:5px;width:100px;">选择签名教练</h5></div>
        <select id="insSel"></select>
    </div>

    <div style="margin-top:5px;">
        <div id='dateSelBox' class="form-row"><h5 style="margin:5px;width:100px;">请选择日期</h5><select id="dateSel"></select></div>
        <div id="dateErr"></div>
    </div>

    

    <div style="margin-left:2px;margin-top:30px;"><button id='submit' onclick="showReport();">生成报告</button></div>
    <hr>

    <div id="planBox" style="display: none;">
        <div id='title'  style="text-indent: 0em;text-align: center;margin-top:50px;"></div>
        <div id="insSig" ></div>
        <!-- <div style="color:#a0a8b0;font-size: 10px;text-indent: 0em;text-align: center;">鹿鹿泽健身</div> -->
        <div id="planDate" style="color:rgb(83, 96, 131);font-size: 10px;text-indent: 0em;text-align: center;"></div>         
        <div id="preTxt" style="margin:10px;"></div>
        <div id="bodyData" ></div>   
        <div id="bodyProblems"></div>
        <div id="cusGoal"></div>
        <div id="insSuggests"></div>
        <div id="stages">
            <div id="stageName"></div>
            <div id="stageGoal"></div>
            <div id="stageDetails"></div>        
        </div>
        <div id="trainSummary"></div>
        <div id="compPic"></div>
        <div id="comPicAlt" style="margin:20px;"></div>
        <div id="postTxt"></div>        
        
    </div>
    <div id="planErrInfo"></div>

    <script src="../static/js/common.js"></script>
    <script src="../static/js/echarts.min.js"></script>
    
    <script>
        let allTrialList;
        let insName;
        let insId;
        let insRole;
        let cusList;
        let insNicknameDic;
        let insSigTxt;
        let pageTxtLib;

        document.addEventListener('DOMContentLoaded',function(){
            // loginCheck();
            document.getElementById('dateSelBox').style.display='none';
            document.getElementById('submit').disabled=true;
            const cusNameList=document.getElementById('cusNameList');
            document.addEventListener("click",function(){
                cusNameList.style.display='none';
            });

            fetch('./get_plan_page_txts')
            .then(response=>response.json())
            .then(data=>{
                // console.log('get txt lib:',data['res']);
                pageTxtLib=data;
            })
            .catch(error=>{
                console.log('获取页面描述文本错误',error);
            })

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                //console.log('cus list:',data);
                cusList=data;
                  })
                .catch(error => console.error('Error:', error));


            fetch('/get_ins_nickname', {
                method: 'GET',
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                
                insNicknameDic=data['ins_nickname_list'];
                //console.log('ins nicknames:',insNicknameDic);

                fetch('/get_ins_list', {
                    method: 'GET',
                    })
                    .then(response => response.json())
                    .then(data => {
                    //将data赋值给块变量cus_list，供后面的handleInput使用
                        console.log('ins list:',data);
                        showInsList(data['ins_list']);
                        generateInsNickName();
                    })
                    .catch(error => console.error('Error:', error));
                })
                .catch(error => console.error('Error:', error));

            
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insId=insInfo.sessionInsId;
            insName=insInfo.sessionInsName;
            insRole=insInfo.sessionInsRole;
            // console.log(insName)
            //教练角色不显示选择框，签名为教练本人，管理员角色显示教练选择框。
            const selectInsBox=document.getElementById('selectInsBox');
            selectInsBox.style.display='none';       

            // console.log('ins sig:',insSigTxt)          
 


        });


        function getPlanDateList(cusIdName){
            // const cusIdName=document.getElementById('cusName');
            
            fetch('/get_train_plan_dates', {
                method: 'POST',
                headers: {
                'Content-Type': 'application/json'
                },
                body:JSON.stringify({'cus_id_name':cusIdName})
                })
            .then(response => response.json())
            .then(data => {
                //将data赋值给块变量cus_list，供后面的handleInput使用
                    // console.log('plan dates list:',data);
                    const planDateList=data['plan_date_list'];
                    const dateSelBox=document.getElementById('dateSelBox');
                    const dateSel=document.getElementById('dateSel');
                    const dateErr=document.getElementById('dateErr');
                    // console.log(planDateList,planDateList.length)
                    if(planDateList.length>0){
                        dateSel.innerText='';
                        document.getElementById('submit').disabled=false;
                        dateSelBox.style.display = 'flex';
                        dateErr.innerHTML='';
                        planDateList.forEach(item=>{
                            const opt=document.createElement('option');
                            opt.value=dateToStringGmt(item,'date');
                            opt.text=dateToStringGmt(item,'date');
                            dateSel.appendChild(opt);
                        });

                        dateSelBox.classList.add('form-row');
                    }else{
                        document.getElementById('submit').disabled=true;
                        dateSelBox.style.display='none';
                        dateErr.innerHTML='<span>该会员未查询到训练计划</span>';
                    }
            })
            .catch(error => console.error('Error:', error));
        }

        function generateInsNickName(){
            if(insRole==='ins'){
                selectInsBox.style.display='none';
                insSigTxt=insNicknameDic[insId+insName];
            }else{
                selectInsBox.style.display='flex';
                insSigTxt=insNicknameDic[document.getElementById('insSel').value];
            }
            //console.log('ins nick name:',insSigTxt);
        }

        function showInsList(insList){
            const insSelect=document.getElementById('insSel');            
            insList.forEach(item=>{
                const opt=document.createElement('option');
                opt.value=item;
                opt.textContent=item.slice(8,);
                insSelect.appendChild(opt);
            });
            insSelect.addEventListener('change',generateInsNickName);
       
            
        }


        function showInsSig(){
            const insSig=document.getElementById('insSig');
            insSig.innerHTML='';
            insSig.innerHTML=`
            <div style='display:flex;justify-content:center;color:#bfbcb6;font-size:12px;margin-top:20px;'>鹿鹿泽健身工作室&nbsp;&nbsp;&nbsp;</div>
            <div style='display:flex;flex-flow:row;justify-content:center;align-items: baseline;'>                
                <div style='color:#3e7ab3;font-size:14px;'> ${insSigTxt}</div>
                <div style='color:#bfbcb6;font-size:8px;'>&nbsp教练</div>
            </div>
            `
        }

        function pickPageTxt(page,pos){       
            const randomIndex = Math.floor(Math.random() * pageTxtLib['res'][page][pos].length); // 生成一个 0 到数组长度减一的随机整数

            const randomTxt = pageTxtLib['res'][page][pos][randomIndex]; // 获取随机索引对应的元素


            return randomTxt; // 输出随机获取的元素
        }

        function handleCusNameInput() {            
            // 获取输入框中的值
            
            const cusName=document.getElementById("cusName");
            const searchTerm = document.getElementById("cusName").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            const resultList=document.getElementById('cusNameList');
            const planBox=document.getElementById('planBox');
            planBox.style.display='none';

            cusName.addEventListener("click", function(event) {
                event.stopPropagation();
            });

            // 清空列表
            resultList.style.display = "block";
            resultList.innerHTML = "";
            
            // if (UpperSearchTerm === "") {
            //     // resultList.style.display = "none";
            //     resultList.style.display = "block";
            //     return; // 输入框为空，不做处理
            // }else{
            //     resultList.style.display = "block";

            // }  
            
            // 遍历给定的数组，进行模糊匹配。倒序
            cusList.reverse().forEach(function(item) {
           
                if (item.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.innerText = item;

                    // 添加点击事件监听器
                    listItem.addEventListener("click", function(event) {
                        event.stopPropagation();
                        // planBox.style.display='none';
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("cusName").value = item;  
                        getPlanDateList(item);
                        resultList.style.display = "none";
                        resultList.innerHTML = "";
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);
                    
                }
            });
            resultList.classList.add('cus-list-result-show');
            resultList.style.top='132px';
            resultList.style.left='232px';
        
            
        }

        function showReport(){
            const cusIdName=document.getElementById('cusName').value;
            const dateSel=document.getElementById('dateSel').value;
            const planBox=document.getElementById('planBox');
            data={
                'cus_id_name':cusIdName,
                'date':dateSel
            }
            fetch('/get_train_plan', {
                method: 'POST',
                headers: {
                'Content-Type': 'application/json'
                },
                body:JSON.stringify(data)
                })
            .then(response => response.json())
            .then(data => {
                // console.log('body and plan:',data);
                //将data赋值给块变量cus_list，供后面的handleInput使用
                if(data['res']==='ok'){
                    const bodyAndPlan=data['body_and_plan'];
                    const stageDetail=data['stage_detail'];
                    planBox.style.display='block';
                    planBox.classList.add('plan-box')
                    showFixedDiv(bodyAndPlan['sex']); //输入性别
                    showBody(bodyAndPlan);
                    showPlan(bodyAndPlan);
                    showStage(bodyAndPlan,stageDetail);
                } else{
                    planBox.style.display='none';
                }                
                    
            })
            .catch(error => console.error('Error:', error));
        }

        function showStage(planData,stageDetail){
            const stageDetails=document.getElementById('stageDetails');
            stageDetails.innerHTML='';
            const stageName=document.getElementById('stageName');
            stageName.innerHTML='';
            stageName.innerHTML=`<div style="display:flex;align-items:center;justify-content:center;width:160px;height:18px;font-size:12px;background:#156dbf;border-radius:4px;color:#FFFFFF;margin-bottom:10px;margin-top:20px;">当前训练阶段 —— <span>${planData['stage']}</span></div>`;
            const stageGoal=document.getElementById('stageGoal');
            stageGoal.innerHTML='';
            stageGoal.innerHTML=`<div style='color:#156dbf;font-size:10px; font-weight:bold;'>&nbsp;&nbsp;本阶段主要目标： <span>${planData['stage_goal']}</span></div>`;
            const titleTxt=['训练目标','训练部位','训练频率','训练强度','训练收益','训练类型','训练时长','激活拉伸时长']
            
            stageDetail.forEach((item,n)=>{
                const dtlCountDiv=document.createElement('div');
                dtlCountDiv.innerHTML=`<div style="display:flex;align-items:center;justify-content:center;width:80px;height:14px;font-size:9px;background:#8e9ead;border-radius:8px;color:#FFFFFF;margin-bottom:4px;margin-top:10px;">阶段目标分解 - ${n+1}</div>`;

                const detailDiv=document.createElement('div');
                detailDiv.id='dtl-'+(n+1);
                item.forEach((detail,k)=>{      
                    // const title=document.createElement('div');
                    // title.innerHTML=`<div>${titleTxt[k]}</div>`;
                    // const div=document.createElement('div');
                    // div.innerHTML=`<div>${item[k]}</div>`;
                    // if(k===2){
                    //     div.innerHTML=`<div>${item[k]} 天/周</div>`;
                    // }
                    // if(k===6){
                    //     div.innerHTML=`<div>${item[k]} 分钟</div>`;
                    // }
                    // if(k===7){
                    //     div.innerHTML=`<div>${item[k]} 分钟</div>`;
                    // }

                    // detailDiv.appendChild(title);
                    // detailDiv.appendChild(div);


                    let divStr=item[k]
                    if(k===2){
                        divStr=`${item[k]} 天/周`;
                    }
                    if(k===6){
                        divStr=`${item[k]} 分钟`;
                    }
                    if(k===7){
                        divStr=`${item[k]} 分钟`;
                    }

                    const itemDiv=document.createElement('div');

                    itemDiv.innerHTML=`         
                            <div>${titleTxt[k]}</div>
                            <div style='color:#647392;'>${divStr}</div>
                            `
                    itemDiv.classList.add('plan-stage-div-grid');
                    detailDiv.appendChild(itemDiv);

                    
                });
                detailDiv.classList.add('plan-stage-div');
                stageDetails.appendChild(dtlCountDiv);
                stageDetails.appendChild(detailDiv);
            });



        }

        function showBody(data){
            const divBodyTitle=document.createElement('div');
            divBodyTitle.innerHTML='<div style="display:flex;align-items:center;justify-content:center;width:90px;height:18px;font-size:12px;background:#156dbf;border-radius:4px;color:#FFFFFF;margin-bottom:10px;">会员身体数据</div>'

            const bodyData=document.getElementById('bodyData');
            bodyData.innerHTML='';
            const divBody=document.createElement('div');
            divBody.id='bodyDataShow';
            divBody.innerHTML=`
                <div class='form-row2' >
                    <div><span class='plan-body-item'>身高</span> &nbsp;&nbsp;&nbsp;${data['ht']} cm</div>
                    <div><span class='plan-body-item'>体重</span> &nbsp;&nbsp;&nbsp;${data['wt']} Kg</div>
                </div>
                <div class='form-row2'>
                    <div><span class='plan-body-item'>体脂率</span> ${(parseFloat(data['bfr'])*100).toFixed(2)} %</div>
                    <div><span class='plan-body-item'>BMI</span>&nbsp;&nbsp;&nbsp;  ${data['bmi']}  </div>
                </div>
                <div class='form-row2' style='margin-top:8px;margin-bottom:8px;'>
                    <div><span class='plan-body-item'>胸围</span>&nbsp;&nbsp;&nbsp; ${data['chest']} cm</div>
                    <div><span class='plan-body-item'>臂围</span>&nbsp;&nbsp;&nbsp; ${data['l_arm']} / ${data['r_arm']} cm</div>
                </div>
                <div class='form-row2' style='margin-top:8px;'>
                    <div><span class='plan-body-item'>腰围</span>&nbsp;&nbsp;&nbsp; ${data['waist']} cm</div>
                    <div><span class='plan-body-item'>臀围</span>&nbsp;&nbsp;&nbsp; ${data['hip']} cm</div>
                </div>
                <div class='form-row2' style='margin-bottom:8px;'>
                    <div><span class='plan-body-item'>腰臀比</span> ${data['waist_hip_ratio']} </div>
                </div>
                <div class='form-row2'style='margin-top:8px;'>
                    <div><span class='plan-body-item'>大腿围</span> ${data['l_leg']} / ${data['r_leg']} cm</div>
                    <div><span class='plan-body-item'>小腿围</span> ${data['l_calf']} / ${data['r_calf']} cm</div>
                </div>
            `
            divBody.classList.add('plan-div');
            divBody.style.color='#647392';
            bodyData.appendChild(divBodyTitle);
            bodyData.appendChild(divBody);

        }

        function showPlan(planData){
            // console.log(planData);
            const bodyProblems=document.getElementById('bodyProblems');
            bodyProblems.innerHTML='';
            const bodyProblemsTitle=document.createElement('div');
            bodyProblemsTitle.innerHTML='<div style="display:flex;align-items:center;justify-content:center;width:106px;height:18px;font-size:12px;background:#156dbf;border-radius:4px;color:#FFFFFF;margin-bottom:10px;margin-top:20px;">会员身体测评结果</div>'            
            const bodyProblemsDiv=document.createElement('div');
            bodyProblemsDiv.innerHTML=`<div>${planData['problems'].replace(/\n/g, '<br>')}</div>`;
            bodyProblemsDiv.classList.add('plan-div');
            bodyProblems.appendChild(bodyProblemsTitle);
            bodyProblems.appendChild(bodyProblemsDiv);

            const cusGoal=document.getElementById('cusGoal');
            cusGoal.innerHTML='';
            const cusGoalTitle=document.createElement('div');
            cusGoalTitle.innerHTML='<div style="display:flex;align-items:center;justify-content:center;width:106px;height:18px;font-size:12px;background:#156dbf;border-radius:4px;color:#FFFFFF;margin-bottom:10px;margin-top:20px;">会员整体训练目标</div>'            
            const cusGoalDiv=document.createElement('div');
            // const cusGoalTxt=planData['cus_goals'].replace(/\n/g, '<br>');
            cusGoalDiv.innerHTML=`<div>${planData['cus_goals'].replace(/\n/g, '<br>')}</div>`;
            cusGoalDiv.classList.add('plan-div');
            // cusGoalDiv.style.color='#5097bf';
            cusGoal.appendChild(cusGoalTitle);
            cusGoal.appendChild(cusGoalDiv);

            const insSuggests=document.getElementById('insSuggests');
            insSuggests.innerHTML='';
            const insSuggestsTitle=document.createElement('div');
            insSuggestsTitle.innerHTML='<div style="display:flex;align-items:center;justify-content:center;width:106px;height:18px;font-size:12px;background:#156dbf;border-radius:4px;color:#FFFFFF;margin-bottom:10px;margin-top:20px;">教练针对性建议</div>'            
            const insSuggestsDiv=document.createElement('div');
            insSuggestsDiv.innerHTML=`<div>${planData['ins_suggests'].replace(/\n/g, '<br>')}</div>`;
            insSuggestsDiv.classList.add('plan-div');
            insSuggests.appendChild(insSuggestsTitle);
            insSuggests.appendChild(insSuggestsDiv);

            const trainSummary=document.getElementById('trainSummary');
            trainSummary.innerHTML='';
            if(planData['train_summary']===''){
                trainSummary.style.display='none';
            }else{
                trainSummary.style.display='flex';
                trainSummary.style.flexDirection='column';
                const trainSummaryTitle=document.createElement('div');
                trainSummaryTitle.innerHTML='<div style="display:flex;align-items:center;justify-content:center;width:106px;height:18px;font-size:12px;background:#156dbf;border-radius:4px;color:#FFFFFF;margin-bottom:10px;margin-top:20px;">训练回顾</div>'            
                const trainSummaryDiv=document.createElement('div');
                trainSummaryDiv.innerHTML=`<div>${planData['train_summary'].replace(/\n/g, '<br>')}</div>`;
                trainSummaryDiv.classList.add('plan-div');
                trainSummary.appendChild(trainSummaryTitle);
                trainSummary.appendChild(trainSummaryDiv);

            }

            const compPics=document.getElementById('compPic');
            const comPicAlt=document.getElementById('comPicAlt');
            compPics.innerHTML='';
            if(planData['comp_pic_url']==='' || planData['comp_pic_url'] === null){
                compPics.style.display='none';
                comPicAlt.innerHTML='';
            }else{
                compPics.style.display='block';
                comPicAlt.innerHTML='<span style="font-size:14px;color:#4d90fa">会员有对比图，正在加载，请等待。</span>'
                fetch('/get_compare_image', {
                    method: 'POST',
                    headers: {
                    'Content-Type': 'application/json'
                    },
                    body:JSON.stringify({'url':planData['comp_pic_url']})
                    })
                .then(response => response.blob()) // 获取二进制数据
                .then(blob => {
                    comPicAlt.innerHTML='';
                    const compPicsTitle=document.createElement('div');
                    compPicsTitle.innerHTML='<div style="display:flex;align-items:center;justify-content:center;width:80px;height:18px;font-size:12px;background:#156dbf;border-radius:4px;color:#FFFFFF;margin-bottom:10px;margin-top:20px;">训练对比图</div>'   
                    const compPicDiv=document.createElement('div');

                    const imageUrl = URL.createObjectURL(blob); 
                    const imgElement=document.createElement('img');
                    imgElement.style.width='200px';
                    imgElement.src = imageUrl;
                    imgElement.alt = '对比图';
                    compPicDiv.classList.add('comp-div');
                    compPicDiv.appendChild(imgElement);

                    compPics.appendChild(compPicsTitle);
                    compPics.appendChild(compPicDiv);
                    
                })
                .catch(error => console.error('Error:', error));
                


            }

        }

        function showFixedDiv(sex){
            const title=document.getElementById('title');
            const planDate=document.getElementById('planDate');
            const dateSelVal=document.getElementById('dateSel').value;
            planDate.innerHTML='';
            planDate.innerHTML=`制定日期：${dateSelVal.slice(0,4)}年${dateSelVal.slice(5,7)}月${dateSelVal.slice(8,10)}日`;
            planDate.style.color='#a0a8b0';
            const nameReport=document.getElementById('cusNameReport');      
            const preTxt=document.getElementById('preTxt');
            const postTxt=document.getElementById('postTxt');  
            const sexTitle=sex==='女'?'女士':'先生'
            title.innerHTML=`<h1 style='color:#3e7ab3'>${document.getElementById('cusName').value.trim().substring(7)}${sexTitle}训练计划</h1>`           
            // nameReport.innerHTML=`<div style='display:flex;align-items:baseline;justify-content:center;width:100px;height:30px;font-size:18px;background:#f5a442;border-radius:4px;color:#FFFFFF;padding-top:5px;margin-bottom:10px;'><span>${document.getElementById('cusName').value.trim().substring(7)}</span> <span style='font-size:10px;'>&nbsp;&nbsp;${sexTitle}</span</div>`
            
            const preTxtStr=pickPageTxt('show_plan.html','pre_txt');
            preTxt.innerHTML=`<div class='plan-page-txt'>${splitTxtToP(preTxtStr)}</div>`;
            preTxt.style.marginBottom='30px';
            const postTxtStr=pickPageTxt('show_plan.html','post_txt');
            postTxt.innerHTML=`<div class='plan-page-txt'>${splitTxtToP(postTxtStr)}</div>`;
            postTxt.style.marginBottom='50px';

            showInsSig();
 
        }

        function splitTxtToP(txt){
            const para=txt.split('\n');
            let res='';
            for(let i=0;i<para.length;i++){
                res+="<p>"+para[i]+"</p>";
            }
            return res
        }

    </script>
  
</body>
</html>
